package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@Slf4j
public class FileUploadController {
    //private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
    //这句话可以省略，让lombok去完成

    @Autowired
    private AliOSSUtils aliOSSUtils;


    @PostMapping("/upload")
    public Result upload(MultipartFile image) {
        try {
            String url = aliOSSUtils.upload(image);
            return Result.success(url);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("上传失败！",e);
            return Result.error("上传失败！");
        }
    }



    //本地存储
    @PostMapping("/fileUpload1")
    public Result fileUpload1(String username, String password, MultipartFile image) {
        log.info(username+","+password+","+image.getOriginalFilename());
        //TODO 保存图片到本地
        String filename = image.getOriginalFilename();//获取文件名称
        String destFile = "/Users/lyc/Desktop/code/Web161/MavenQuickStart/tlias-web-management/images/"
                + UUID.randomUUID()+filename;
        //保存文件
        try {
            InputStream netIn = image.getInputStream();

            //完成图片的拷贝
            //Commons-io完成
            FileUtils.copyInputStreamToFile(netIn,new File(destFile));

           /* FileOutputStream fos = new FileOutputStream(destFile);

            byte[] buf = new byte[1024 * 8];
            int len;
            while ((len = netIn.read(buf))!=-1){
                fos.write(buf,0,len);
            }

            fos.close();*/


            return Result.success();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }



    }


    //阿里云存储
    @PostMapping("/fileUpload")
    public Result fileUpload(String username, String password, MultipartFile image) {
        log.info(username+","+password+","+image.getOriginalFilename());
        //TODO 保存图片到本地
        String url = null;
        try {
            url = aliOSSUtils.upload(image);
            return Result.success(url);
        } catch (IOException e) {
//            e.printStackTrace();
            log.error("云存储失败！",e);
            return Result.error("云存储失败！");
        }

    }




}
